<template>
  <div>
    <div id="profilePhoto" style="border: solid 1px red">
      <el-upload
          class="avatar-uploader"
          accept="image/jpeg,image/png"
          action="http://localhost:9191/user/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>

    <div id="info_body">
      <el-form ref="updateForm" :model="userInfo">
        <el-form-item label="用户昵称">
          <el-input type="text" style="width: 300px" v-model="userInfo.username" autocomplete="off"
                    :disabled="!nameShow"></el-input>
          &nbsp;
          <el-button type="primary" @click="showUpdateName()" v-if="!nameShow">修改</el-button>
          <el-button type="primary" @click="update()" v-if="nameShow">确认</el-button>
        </el-form-item>
        <el-form-item label="登陆密码">
          <el-input type="password" style="width: 300px" v-model="userInfo.password" autocomplete="off"
                    disabled></el-input>
          &nbsp;
          <el-button type="primary" @click="updatePassword()">修改</el-button>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input type="text" style="width: 300px" v-model="userInfo.phoneNumber" autocomplete="off"
                    disabled></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!--修改密码对话框-->
    <el-dialog title="修改密码" :visible.sync="updateFormVisible" @close="closeUpdateForm" :close-on-click-modal="false">

      <!--具体表单-->
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="原密码" prop="oldPass">
          <el-input v-model="ruleForm.oldPass"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleForm.oldPass,ruleForm.pass,ruleForm.checkPass)">确定
          </el-button>
          <el-button @click="closeUpdateForm">取 消</el-button>
          <el-button @click="forgetPassword">忘记原密码？</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!--手机号修改密码-->
    <el-dialog title="手机号修改密码" :visible.sync="updateFormVisible2" @close="closeUpdateForm2"
               :close-on-click-modal="false">

      <!--具体表单-->
      <el-form :model="ruleForm" status-icon :rules="rules" ref="captchaForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="绑定的手机号" prop="phoneNumber">
          <el-input v-model="userInfo.phoneNumber" disabled></el-input>
        </el-form-item>
        <el-form-item label="输入验证码" prop="captcha">
          <el-input type="text" v-model="captcha"></el-input>
          <span class="show-pwd">
            <el-button :loading="sending" size="small" @click="onSendSms">发送验证码</el-button>
          </span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm2(userInfo.phoneNumber, captcha)">确定
          </el-button>
          <el-button @click="closeUpdateForm2">取 消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


  </div>
</template>

<script>
export default {
  inject: ["reload"],
  name: "UserInfo",
  data() {

    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: '',
        checkPass: '',
        oldPass: ''
      },
      rules: {
        pass: [
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
            message: "不能为空，长度8-20位，必须包含英文大小写+数字",
            trigger: 'blur'
          },
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {required: true, trigger: "blur"},
          {validator: validatePass2, trigger: 'blur'}
        ],
        oldPass: [{required: true, message: "原密码不能为空！", trigger: "blur"}],
      },
      updateFormVisible: false,
      updateFormVisible2: false,
      imageUrl: '',
      userInfo: {
        profilePhoto: '',
        username: '',
        phoneNumber: '',
        password: '',
      },
      nameShow: false,
      timer: 0,
      captcha: '',
      sending: false,
    };
  },
  methods: {
    showUpdateName() {
      this.nameShow = true;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      let token = sessionStorage.getItem("token");

      let data = {
        token: token,
        fileName: res.data
      }

      this.$axios.postForm("/user/updateProfilePhoto", data)
          .then(response => {
            let responseData = response.data;
            if (responseData.code === 200) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 2000,
              })
              this.reload();
            }
          })
    },
    closeUpdateForm() {
      this.updateFormVisible = false;
      this.$refs.ruleForm.resetFields();
    },
    closeUpdateForm2() {
      this.updateFormVisible2 = false;
      this.$refs.ruleForm.resetFields();
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      let boo = true;
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
        boo = false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return true;
    },

    loginUserInfo() {
      let token = sessionStorage.getItem("token");
      this.$axios.get("/user/getLoginUser", {params: {token: token}})
          .then(response => {
            let responseData = response.data;
            this.userInfo = responseData.data;
            this.imageUrl = this.userInfo.profilePhoto;
          })
    },

    update() {
      let token = sessionStorage.getItem("token");
      this.$axios.postForm("/user/updateUser", this.userInfo, {params: {token: token}})
          .then(response => {
            let responseData = response.data;

            if (responseData.code === 200) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 2000,
              })
              sessionStorage.setItem("isShowMainBody",false);
              this.reload();
            }
          })
    },
    submitForm(oldPass, pass, checkPass) {
      if (pass !== checkPass) {
        alert("两次密码不一致！");
        return;
      }
      this.$refs.ruleForm.validate(isValid => {
        if (!isValid) {
          this.$message({
            message: "请正确填写",
            type: "error",
            duration: 2000,
          })
          return;
        } else {
          this.$axios.get("/user/password", {params: {pass: oldPass}})
              .then(response => {
                let responseData = response.data;
                let encryptedPassword = responseData.data;
                if (encryptedPassword !== this.userInfo.password) {
                  alert("与原来的密码不匹配");
                  return;
                }
                this.userInfo.password = pass;
                this.update();
                this.$axios.post("/user/logout").then(response => {
                  if (response.data.code == 200) {
                    sessionStorage.removeItem("token");
                    this.$router.push("/Login")
                  }
                })
              })
        }
      })
    },
    updatePassword() {
      this.updateFormVisible = true;
    },
    forgetPassword() {
      this.updateFormVisible = false;
      this.updateFormVisible2 = true;
    },
    onSendSms() {
      this.$axios.postForm("/user/sendForgetPasswordCode", {phoneNumber: this.userInfo.phoneNumber})
          .then(response => {
            if (response.data.code == 200) {
              this.sending = true;
              const {phoneNumber} = this.userInfo.phoneNumber;
              this.$message({
                message: "短信已发送成功，请注意查收",
                type: "success",
                duration: 2000,
              })
              this.timer = 60;
              this.sending = true;

            }
          });
    },
    submitForm2(phoneNumber, captcha) {
      this.$axios.postForm("/user/updatePasswordByPhoneNumber", {
        phoneNumber: phoneNumber,
        captcha: captcha
      }).then(response => {
        if (response.data.code == 200) {
          this.$alert("修改成功！初始密码为" + response.data.data + "！请牢记！可使用初始密码修改新的密码")
          this.$axios.post("/user/logout").then(response => {
            if (response.data.code == 200) {
              sessionStorage.removeItem("token");
              this.$router.push("/Login")
            }
          })
        } else {
          this.$message({
            message: response.data.msg,
            type: "error",
            duration: 2000,
          })
        }
      })
    }
},
watch: {
  timer(num)
  {
    if (num > 0) {
      setTimeout(() => {
        this.timer = --num;
      }, 1000);
    }
  }
,
}
,
activated()
{
  this.loginUserInfo();
}
}

</script>

<style scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  border-radius: 90px;
  width: 178px;
  height: 178px;
  display: block;
}

#profilePhoto {
  border-radius: 90px;
  width: 178px;
  height: 178px;
  position: relative;
  top: 70px;
  left: 130px;
}

#info_body {
  width: 600px;
  position: relative;
  left: 400px;
  bottom: 120px;
}

</style>